//
//  AppDelegate.m
//  XiangMi_Novel
//
//  Created by Botao on 2019/1/14.
//  Copyright © 2019 zk. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarViewController.h"
#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import "IQKeyboardManager.h"
#import "PhoneLoginViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 获取设备唯一标识的方法，NSUUID+KeyChain的方法
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"isSaveUUID"]){
        NSString *UUID = [[NSUUID UUID] UUIDString];
        BOOL isSuccess = [SAMKeychain setPassword:UUID forService:@"com.yourcompany.yourapp" account:@"user"];
        if (isSuccess) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isSaveUUID"];
        }
    }
    
    // UMConfigure 通用设置，请参考SDKs集成做统一初始化。
    [self configUSharePlatforms:launchOptions];
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    keyboardManager.shouldShowTextFieldPlaceholder = YES; // 是否显示占位文字
    keyboardManager.keyboardDistanceFromTextField = 10.0f; // 输入框距离键盘的距离
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([self isIphoneXSeries] == YES) {
        [user setInteger:1 forKey:@"isIphoneXSeries"];
    }else{
        [user setInteger:0 forKey:@"isIphoneXSeries"];
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:NO forKey:@"isIosFlag=1"];
    
    //1首次安装,2非首次
    if ([userDefaults objectForKey:@"installNumber"] == nil) {
        [userDefaults setInteger:1 forKey:@"installNumber"];
    }else{
        [userDefaults setInteger:2 forKey:@"installNumber"];
    }
    
    //ios甄别审核接口 初始化tabbar
    [self iosFlag];
    
    //[userDefaults setBool:YES forKey:@"sureLogin"];
    self.window.rootViewController = [[TabBarViewController alloc]init];
    
    return YES;
}

//ios甄别审核接口
- (void)iosFlag
{
    [[HttpManager shareInstance] getFlagParam:@{} Complete:^(NSInteger code, NSDictionary *dic)
     {
         NSLog(@"dic = %@",dic);
         NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
         NSString *result = [NSString stringWithFormat:@"%@",[dic objectForKey:@"result"]];
         if (dic == nil) {
             result = @"1";
         }
         if ([result isEqualToString:@"1"]) {
             //注释表示不隐藏
//             [userDefaults setBool:YES forKey:@"isIosFlag=1"];
         }
         //加载选项卡
         if ([userDefaults integerForKey:@"installNumber"] == 1) {
             self.window.rootViewController = [[TabBarViewController alloc]init];
             //self.window.rootViewController = [[PhoneLoginViewController alloc] init];
         }else{
             self.window.rootViewController = [[TabBarViewController alloc]init];
         }
     }];
}

#pragma UMShare
- (void)configUSharePlatforms:(NSDictionary *)launchOptions
{
    [UMConfigure initWithAppkey:UM_APPKEY channel:@"App Store"];
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WX_AppID appSecret:WX_APPSecret redirectURL:@"http://mobile.umeng.com/social"];
    /*设置QQ平台的appID*/
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQ_AppID  appSecret:QQ_APP_Key redirectURL:@"http://mobile.umeng.com/social"];
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:WeiBo_Appkey appSecret:WeiBo_AppSecret redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}

// 适用于 ios 9以上
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        
    }
    return result;
}


- (BOOL)isIphoneXSeries
{
    UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
    if (@available(iOS 11.0, *)) {
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            return YES;
        }
    } else {
        // Fallback on earlier versions
    }
    return NO;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"XiangMi_Novel"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}


#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

// 获取 document 目录
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

// 加载 ManagedObjectModel
- (NSManagedObjectModel *)managedObjectModel {
    if (!_managedObjectModel) {
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"XiangMi_Novel" withExtension:@"momd"];
        _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    }
    return _managedObjectModel;
}

// 创建 PersistentStoreCoordinator
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (!_persistentStoreCoordinator) {
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"UserCoreData.sqlite"];
        NSError *error = nil;
        [_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
        if (error) {
            NSLog(@"falied to create persistentStoreCoordinator %@", error.localizedDescription);
        }
    }
    return _persistentStoreCoordinator;
}

// 创建 ManagedObjectContext
/*
 NSMainQueueConcurrencyType 的 context 用于响应 UI 事件，
 NSPrivateQueueConcurrencyType 的 context 用于涉及大量数据操作可能会阻塞 UI 的。
 */
- (NSManagedObjectContext *)managedObjectContext {
    if (!_managedObjectContext) {
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_managedObjectContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
    }
    return _managedObjectContext;
}

@end
